import { Provide, Inject, Config } from '@midwayjs/decorator';
import { MidwayHttpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { CacheManager } from '@midwayjs/cache';
import * as qiniu from 'qiniu';
import { config } from './../utils/config';
// import WechatPay from './../utils/pay';

const svgCaptcha = require('svg-captcha');

@Provide()
export class CommonService {
  @Config('jwt')
  config: any;

  @Inject()
  ctx: Context;

  @Inject()
  cacheManager: CacheManager;

  async getCode(data: any) {
    const captcha = svgCaptcha.create({
      inverse: false, // 翻转颜色
      fontSize: 46, // 字体大小
      noise: 2, // 干扰线条数
      width: 120, // 宽度
      height: 40, // 高度
      size: 4, // 验证码长度
      ignoreChars: '0o1i', // 验证码字符中排除 0o1i
      color: true, // 验证码是否有彩色
      background: '#cc9966', // 验证码图片背景颜色
    });

    this.cacheManager.set(data.key, captcha.text.toLowerCase(), {
      ttl: 100,
    });

    if (!captcha) {
      throw new MidwayHttpError('请求验证码错误!', 500);
    }

    return {
      code: 200,
      data: captcha.data,
      codeText: captcha.text.toLowerCase(),
      message: '获取验证码成功!',
    };
  }

  async getQiniuToken() {
    const accessKey = config.qiniu.AccessKey;
    const secretKey = config.qiniu.SecretKey;
    const bucket = 'wenjieqiniu';
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const options = {
      scope: bucket,
      expires: 72000,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);

    const uploadToken = putPolicy.uploadToken(mac);

    return {
      code: 200,
      data: uploadToken,
      message: '获取成功!',
    };
  }
}
